/* ----------------------------------------------------------------------------
* File: user_profile_impl.cpp
*
* Desc: Implementation for user profile - definition
*
* Created: 07/05/2011, by Alexey Korshunov
* ---------------------------------------------------------------------------- */
#include "user_profile_impl.h"
#include <fstream>


namespace ModuleManagement
{
	UserProfileImpl::UserProfileImpl(const std::string& FileName) throw(Common::Exception)
		: m_UserFile(FileName)
	{
		std::fstream file;
		char str[512];
		char *name = NULL, *points = NULL;

		// Open file
		file.open(FileName.c_str());
		if (!file.is_open())
			throw Common::Exception("skype_plugin: ERROR - Unable to open user profile file");

		// Read data
		while(file.good())
		{
			file.getline(str, sizeof(str));

			name = strtok(str, "|");
			points = strtok(NULL, "|");

			UserInfo *info = new UserInfo;
			info->name.append(name);
			info->points = atoi(points);
			m_UserInfo.push_back(info);
		}
		file.close();
	}

	UserProfileImpl::~UserProfileImpl()
	{
		// Write user info
		WriteUserInfo();

		VectorUserInfoIterator it_user = m_UserInfo.begin();
		for (; it_user != m_UserInfo.end(); ++it_user)
			delete *it_user;
		m_UserInfo.clear();
	}

	int UserProfileImpl::GivePoints(const std::string& User, unsigned int Points)
	{
		bool found = false;
		size_t i = 0;

		// Find user
		size_t num = m_UserInfo.size();
		for (i = 0; i < num; ++i)
		{
			if (m_UserInfo[i]->name == User)
			{
				found = true;
				break;
			}
		}

		if (!found)
		{
			UserInfo *info = new UserInfo;
			info->name = User;
			info->points = Points;
			m_UserInfo.push_back(info);
		}
		else
			m_UserInfo[i]->points += Points;

		return 0;
	}


	void UserProfileImpl::WriteUserInfo()
	{
		std::fstream file;

		file.open(m_UserFile.c_str());
		if (file.is_open())
		{
			size_t num = m_UserInfo.size();
			for (size_t i = 0; i < num; ++i)
			{
				UserInfo *info = m_UserInfo[i];
				file << info->name.c_str() << "|" << info->points << std::endl;
			}
			file.close();
		}
	}
}

